//    在程序重新进入并再开始下载的时候它会把cache 中的数据重新复制到tmp中。

//    nsurlsession文件存储到本地时,会自动生成一个随机的文件名，这个可以不考虑重名问题，苹果会处理好。

//    在删除文件的时候通过读取本地文件 resumedata 这个文件中包涵了下载中文件的所有信息 , 包括苹果自动生成的文件名,在文件没下载完成的情况下删除文件，只需要拿到文件名，然后在对应的路径下删除相应的文件即可.
//程序中途退出再进
#import "DownLoadOpration.h"
#import "AppDelegate.h"
#import "PhoneInsideStoreCount.h"
#define  ContentLocations [NSString stringWithFormat:@"%@/Documents/%@/%@",NSHomeDirectory(),_userflag,_storagePath]
@interface DownLoadOpration ()<CoreStatusProtocol>
//获取上次加载的大小
//在这里将所有的文件都保存到Doc/userflag/storagePath中,如果要想删除一个文件和多个文件时可以直接在这个文件夹中删除/而且想要全部删除的时候可以直接清空一个文件夹即可
@property (nonatomic,assign)CGFloat lastByte;
@property(nonatomic,copy)NSString * url;
@property(nonatomic,copy)NSString * user;
@property(nonatomic,copy)NSString * local;
@property(nonatomic,copy)NSString * systemVision;
@property (nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)float timeCount;
@property(nonatomic,assign)BOOL isBackground;
@property(nonatomic,assign)BOOL isTap;
@property(nonatomic,copy)NSString * stopName;
//@property (nonatomic,strong)NSTimer *downTimer;
//@property(nonatomic,assign)CGFloat downbyte;
//@property(nonatomic,assign)CGFloat compairebyte;
//@property(nonatomic,assign)NSInteger count;

@end
static DownLoadOpration *downLoadOpration = nil;
@implementation DownLoadOpration
-(instancetype)init
{
    if (self = [super init]) {
        _storagePathMuArr = [NSMutableArray array];
        _downPathMuArr = [NSMutableArray array];
        _messagessDic = [NSMutableDictionary dictionary];
        _stopDownpathArr = [NSMutableArray array];
        _stopStorageArr = [NSMutableArray array];
        _messagessDic[@"downcondition"] = @"";
        _messagessDic[@"allsize"] = @"";
        _messagessDic[@"contentsize"] = @"";
        _messagessDic[@"progress"] = @"";
        _timeCount = 0;
        isDownLoading = NO;
        _systemVision =  [[UIDevice currentDevice] systemVersion];
        _isBackground = NO;
        //_isTap = NO;
#pragma marks-----添加程序退出监听
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitThePrograma:) name:UIApplicationWillTerminateNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backgroundChange:) name:UIApplicationWillResignActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(forground:) name:UIApplicationDidBecomeActiveNotification object:nil];
    }
    return self;
}
-(void)forground:(NSNotification *)notify
{
    _isBackground = NO;
    if (_timer)
    {
        [_timer setFireDate:[NSDate distantFuture]];
    }
}
+(instancetype)getInstance
{
    @synchronized(self)
    {
        if(!downLoadOpration)
        {
            downLoadOpration = [[self alloc] init];
        }
    }
    return downLoadOpration;
}

-(void)downloadFileWith:(NSMutableArray *)urlArray
{
    if (![_downpath isEqualToString:@""] && [urlArray containsObject:_downpath]) {
        if (isDownLoading == NO)
        {
            [self resumeTask];
        }
    }else
    {
        _localName = _storagePathMuArr.firstObject;
        _downpath = _downPathMuArr.firstObject;
        [[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat:@"%@",ContentLocations] withIntermediateDirectories:YES attributes:nil error:nil];
//        NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:
        NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
        sessional = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:mainQueue];
        NSString *locaFile = [NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject];
        NSData *data = [NSData dataWithContentsOfFile:locaFile];
        if (data) {
            NSData * resumeData = [self getCorrectResumeData:data];
            if (resumeData) {
                _task =[sessional downloadTaskWithResumeData:resumeData];
            }
        }
        else
            //    新建下载任务
            _task =[sessional downloadTaskWithURL:[NSURL URLWithString:urlArray.firstObject]];
        _messagessDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject]];
        if (_messagessDic == nil || [_messagessDic allKeys] == 0) {
            _messagessDic = [NSMutableDictionary dictionary];
            _messagessDic[@"downcondition"] = @"";
            _messagessDic[@"allsize"] = @"";
            _messagessDic[@"contentsize"] = @"";
            _messagessDic[@"progress"] = @"";
        }
        _messagessDic[@"downcondition"] = @"download";
        [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
        //    启动下载任务
        [_task resume];
        _lastName = _localName;
    }
    isDownLoading = YES;
    //    [self netJuge];
    [CoreStatus beginNotiNetwork:self];
    //    if(!_downTimer)
    //    {
    //        _downTimer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(restore) userInfo:nil repeats:YES];
    //        _count = 0;
    //    }
    //    if (_timer) {
    //        [_timer invalidate];
    //        _timer = nil;
    //    }
}
-(void)dealloc
{
    [CoreStatus endNotiNetwork:self];
    _delegate = nil;
    _downloadProgressBlock = nil;
    _downloadSuccessBlock = nil;
    _downloadFailureBlock = nil;
    _netBeakBlock = nil;
    _pausefinishBolock = nil;
    _restartfinishBlock = nil;
    _deletfinishBlock = nil;
    _allstartcomplete = nil;
    _allstopcompelete = nil;
    _exitsuccess = nil;
    _alldeletsuccess = nil;
    _lastCount = nil;
}
//-(void)restore
//{
//    if (_count == 0) {
//        _compairebyte = _downbyte;
//        _count ++;
//    }else if (_count == 1)
//    {
//        _count ++;
//    }else if(_count == 2) {
//        if (isDownLoading == YES) {
//            if (_compairebyte == _downbyte) {
//                [_task cancel];
//                _task = nil;
//                NSData *data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject]];
//                NSData *resumeData;
//                if (data) {
//                    resumeData = [self getCorrectResumeData:data];
//                }
//                if(!sessional)
//                {
//                    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:[self getUniqueStrByUUID]];
//                    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
//                    sessional = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:mainQueue];
//                }
//                if (resumeData) {
//                    _task =[sessional downloadTaskWithResumeData:resumeData];
//                }else
//                {
//                    _task = [sessional downloadTaskWithURL:[NSURL URLWithString:_downpath]];
//                }
//                _messagessDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject]];
//                if (_messagessDic == nil || [_messagessDic allKeys] == 0) {
//                    _messagessDic = [NSMutableDictionary dictionary];
//                    _messagessDic[@"downcondition"] = @"";
//                    _messagessDic[@"allsize"] = @"";
//                    _messagessDic[@"contentsize"] = @"";
//                    _messagessDic[@"progress"] = @"";
//                }
//                _messagessDic[@"downcondition"] = @"download";
//                [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
//                //启动任务
//                [_task resume];
//                _lastName = _localName;
//                isDownLoading = YES;
//            }
//        }
//        _count = 0;
//    }
//}
- (NSData *)getCorrectResumeData:(NSData *)resumeData {
    NSData *newData = nil;
    NSString *kResumeCurrentRequest = @"NSURLSessionResumeCurrentRequest";
    NSString *kResumeOriginalRequest = @"NSURLSessionResumeOriginalRequest";
    //获取继续数据的字典
    NSMutableDictionary* resumeDictionary = [NSPropertyListSerialization propertyListWithData:resumeData options:NSPropertyListMutableContainers format:NULL error:nil];
    //重新编码原始请求和当前请求
    resumeDictionary[kResumeCurrentRequest] = [self correctRequestData:resumeDictionary[kResumeCurrentRequest]];
    resumeDictionary[kResumeOriginalRequest] = [self correctRequestData:resumeDictionary[kResumeOriginalRequest]];
    newData = [NSPropertyListSerialization dataWithPropertyList:resumeDictionary format:NSPropertyListBinaryFormat_v1_0 options:NSPropertyListMutableContainers error:nil];
    return newData;
}

- (NSData *)correctRequestData:(NSData *)data {
    NSData *resultData = nil;
    NSData *arData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    if (arData != nil) {
        return data;
    }
    NSMutableDictionary *archiveDict = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainersAndLeaves format:nil error:nil];
    int k = 0;
    NSMutableDictionary *oneDict = [NSMutableDictionary dictionaryWithDictionary:archiveDict[@"$objects"][1]];
    while (oneDict[[NSString stringWithFormat:@"$%d", k]] != nil) {
        k += 1;
    }
    int i = 0;
    while (oneDict[[NSString stringWithFormat:@"__nsurlrequest_proto_prop_obj_%d", i]] != nil) {
        NSString *obj = oneDict[[NSString stringWithFormat:@"__nsurlrequest_proto_prop_obj_%d", i]];
        if (obj != nil) {
            [oneDict setObject:obj forKey:[NSString stringWithFormat:@"$%d", i + k]];
            [oneDict removeObjectForKey:obj];
            archiveDict[@"$objects"][1] = oneDict;
        }
        i += 1;
    }
    if (oneDict[@"__nsurlrequest_proto_props"] != nil) {
        NSString *obj = oneDict[@"__nsurlrequest_proto_props"];
        [oneDict setObject:obj forKey:[NSString stringWithFormat:@"$%d", i + k]];
        [oneDict removeObjectForKey:@"__nsurlrequest_proto_props"];
        archiveDict[@"$objects"][1] = oneDict;
    }
    NSMutableDictionary *twoDict = [NSMutableDictionary dictionaryWithDictionary:archiveDict[@"$top"]];
    if (twoDict[@"NSKeyedArchiveRootObjectKey"] != nil) {
        [twoDict setObject:twoDict[@"NSKeyedArchiveRootObjectKey"] forKey:[NSString stringWithFormat:@"%@", NSKeyedArchiveRootObjectKey]];
        [twoDict removeObjectForKey:@"NSKeyedArchiveRootObjectKey"];
        archiveDict[@"$top"] = twoDict;
    }
    resultData = [NSPropertyListSerialization dataWithPropertyList:archiveDict format:NSPropertyListBinaryFormat_v1_0 options:NSPropertyListMutableContainers error:nil];
    return resultData;
}
-(void)timerRun
{
    _timeCount += 0.2;
}
- (NSString *)getUniqueStrByUUID {
    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
    CFStringRef uuidStrRef= CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    NSString *retStr = [NSString stringWithString:(__bridge NSString * _Nonnull)(uuidStrRef)];
    CFRelease(uuidStrRef);
    return retStr;
}
-(void)pauseTaskWithLocalPath:(NSString *)localPath
{
    if ([localPath isEqualToString:_localName]) {
        if (_task && ![_downpath isEqualToString:@""])
        {
            //__weak typeof(self) ws=self;
            //    取消下载任务
            //            _isTap = YES;
            [_task cancelByProducingResumeData:^(NSData *resumeData) {
                //resumeData包含暂停下载的位置和下载的url(一个很小的文件)
                [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[localPath componentsSeparatedByString:@"."].firstObject] atomically:YES];
                _messagessDic[@"downcondition"] = @"pause";
                [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
                [_stopDownpathArr addObject:[_downpath mutableCopy]];
                [_stopStorageArr addObject:[_localName mutableCopy]];
                [_downPathMuArr removeObject:_downpath];
                [_storagePathMuArr removeObject:_localName];
                [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
                [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
                [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
                [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
                _localName = nil;
                _downpath = nil;
                if (_downPathMuArr.count >= 1 )
                {
                    NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_storagePathMuArr[0] componentsSeparatedByString:@"."].firstObject]];
                    if ([messageDic[@"progress"] floatValue] != 0) {
                        _localName = _storagePathMuArr[0];
                        _downpath = _downPathMuArr[0];
                        [self resumeTask];
                    }else
                    {
                        _downpath = nil;
                        _localName = nil;
                        [self downloadFileWith:_downPathMuArr];
                    }
                }
                else
                {
                    isDownLoading = NO;
                    _localName = nil;
                    _downpath = nil;
                }
                if (_pausefinishBolock) {
                    _pausefinishBolock();
                }
            }];
        }
    }else
    {
        if ([_storagePathMuArr containsObject:localPath]) {
            NSInteger index = [_storagePathMuArr indexOfObject:localPath];
            NSString *url = [[_downPathMuArr objectAtIndex:index] mutableCopy];
            [_storagePathMuArr removeObjectAtIndex:index];
            [_stopStorageArr addObject:localPath];
            [_stopDownpathArr addObject:url];
            [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
            [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
            [_downPathMuArr removeObjectAtIndex:index];
            [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
            [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
            NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[localPath componentsSeparatedByString:@"."].firstObject]];
            if (messageDic == nil || [messageDic allKeys] == 0) {
                messageDic = [NSMutableDictionary dictionary];
                messageDic[@"downcondition"] = @"pause";
                messageDic[@"allsize"] = @"";
                messageDic[@"contentsize"] = @"";
                messageDic[@"progress"] = @"";
            }else
            {
                messageDic[@"downcondition"] = @"pause";
            }
            [messageDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[localPath componentsSeparatedByString:@"."].firstObject] atomically:YES];
            if (_pausefinishBolock) {
                _pausefinishBolock();
            }
        }else
        {
            if (_pausefinishBolock) {
                _pausefinishBolock();
            }
        }
    }
}
//-(void)puseLocal
//{
//    [_task cancelByProducingResumeData:^(NSData *resumeData) {
//        //resumeData包含暂停下载的位置和下载的url(一个很小的文件)
//        [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
//        _messagessDic[@"downcondition"] = @"pause";
//        [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
//        [_stopDownpathArr addObject:[_downpath mutableCopy]];
//        [_stopStorageArr addObject:[_localName mutableCopy]];
//        [_downPathMuArr removeObject:_downpath];
//        [_storagePathMuArr removeObject:_localName];
//        [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
//        [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
//        [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
//        [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
//        _localName = nil;
//        _downpath = nil;
//        if (_downPathMuArr.count >= 1 )
//        {
//            NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_storagePathMuArr[0] componentsSeparatedByString:@"."].firstObject]];
//            if ([messageDic[@"progress"] floatValue] != 0) {
//                _localName = _storagePathMuArr[0];
//                _downpath = _downPathMuArr[0];
//                [self resumeTask];
//            }else
//            {
//                _downpath = nil;
//                _localName = nil;
//                [self downloadFileWith:_downPathMuArr];
//            }
//        }
//        else
//        {
//            isDownLoading = NO;
//            _localName = nil;
//            _downpath = nil;
//        }
//        _pausefinishBolock();
//        _isTap = NO;
//    }];
//
//}
-(void)restartTaskWithLocalPath:(NSString *)localPath
{
    if ([_stopStorageArr containsObject:localPath]) {
        NSInteger index = [_stopStorageArr indexOfObject:localPath];
        NSString * url = [[_stopDownpathArr objectAtIndex:index] mutableCopy];
        [_stopDownpathArr removeObjectAtIndex:index];
        [_stopStorageArr removeObjectAtIndex:index];
        [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
        [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
        [_storagePathMuArr addObject:localPath];
        [_downPathMuArr addObject:url];
        [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
        [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
        NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[localPath componentsSeparatedByString:@"."].firstObject]];
        if (isDownLoading == NO) {
            if ([messageDic[@"progress"] floatValue] != 0) {
                _localName = localPath;
                _downpath = url;
                [self resumeTask];
            }else
            {
                _downpath = nil;
                _localName = nil;
                [self downloadFileWith:_downPathMuArr];
            }
            messageDic[@"downcondition"] = @"download";
        }else
        {
            messageDic[@"downcondition"] = @"wait";
        }
        [messageDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[localPath componentsSeparatedByString:@"."].firstObject] atomically:YES];
        if (_restartfinishBlock) {
            _restartfinishBlock();
        }
    }else if ([_storagePathMuArr containsObject:localPath])
    {
        NSInteger index = [_storagePathMuArr indexOfObject:localPath];
        _downpath = [[_downPathMuArr objectAtIndex:index] mutableCopy];
        _localName = localPath;
        [self resumeTask];
        
        if (_restartfinishBlock) {
            _restartfinishBlock();
        }
    }else
    {
        if (_restartfinishBlock) {
            _restartfinishBlock();
        }
    }
}
//全部暂停
-(void)allStop
{
    if (_storagePathMuArr.count != 0)
    {
        if (isDownLoading == YES)
        {
            if (_task) {
                __weak typeof(self) ws=self;
                //    取消下载任务
                [_task cancelByProducingResumeData:^(NSData *resumeData)
                 {
                     [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
                     ws.task=nil;
                     for (NSString *storagePath in _storagePathMuArr) {
                         NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject]];
                         if (messagedic == nil) {
                             messagedic = [NSMutableDictionary dictionary];
                             messagedic[@"allsize"] = @"";
                             messagedic[@"contentsize"] = @"";
                             messagedic[@"progress"] = @"";
                         }
                         messagedic[@"downcondition"] = @"pause";
                         [messagedic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject] atomically:YES];
                     }
                     //将所有的队列中的数据变成暂停队列中的数据
                     [_stopDownpathArr addObjectsFromArray:[_downPathMuArr mutableCopy]];
                     [_stopStorageArr addObjectsFromArray:[_storagePathMuArr mutableCopy]];
                     _downPathMuArr = [NSMutableArray array];
                     _storagePathMuArr = [NSMutableArray array];
                     [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
                     [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
                     [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
                     [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
                     isDownLoading = NO;
                     if (_allstopcompelete) {
                         _allstopcompelete();
                     }
                 }];
            }
            else
            {
                isDownLoading = NO;
                if (_allstopcompelete) {
                    _allstopcompelete();
                }
            }
        }else
        {
            isDownLoading = NO;
            if (_allstopcompelete) {
                _allstopcompelete();
            }
        }
    }else
    {
        isDownLoading = NO;
        if (_allstopcompelete) {
            _allstopcompelete();
        }
    }
}
//全部开始
-(void)allStart
{
    [_downPathMuArr addObjectsFromArray:[_stopDownpathArr mutableCopy]];
    [_storagePathMuArr addObjectsFromArray:[_stopStorageArr mutableCopy]];
    _stopDownpathArr = [NSMutableArray array];
    _stopStorageArr = [NSMutableArray array];
    [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
    [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
    [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
    [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
    if (isDownLoading) {
        for (NSString *storagePath in _storagePathMuArr) {
            NSInteger index = [_storagePathMuArr indexOfObject:storagePath];
            NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_storagePathMuArr[index] componentsSeparatedByString:@"."].firstObject]];
            if (messagedic == nil || [messagedic allKeys].count == 0) {
                messagedic = [NSMutableDictionary dictionary];
            }
            if (index == 0) {
                messagedic[@"downcondition"] = @"download";
            }else
            {
                messagedic[@"downcondition"] = @"wait";
            }
            [messagedic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_storagePathMuArr[index] componentsSeparatedByString:@"."].firstObject] atomically:YES];
        }
    }else
    {
        for (NSString *storagePath in _storagePathMuArr) {
            NSInteger index = [_storagePathMuArr indexOfObject:storagePath];
            NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_storagePathMuArr[index] componentsSeparatedByString:@"."].firstObject]];
            if (messagedic == nil || [messagedic allKeys].count == 0) {
                messagedic = [NSMutableDictionary dictionary];
            }
            if (index == 0) {
                messagedic[@"downcondition"] = @"download";
            }else
            {
                messagedic[@"downcondition"] = @"wait";
                
            }
            [messagedic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_storagePathMuArr[index] componentsSeparatedByString:@"."].firstObject] atomically:YES];
        }
        NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_storagePathMuArr[0] componentsSeparatedByString:@"."].firstObject]];
        if ([messagedic[@"progress"] floatValue] != 0) {
            _localName = _storagePathMuArr[0] ;
            _downpath = _downPathMuArr[0];
            [self resumeTask];
        }else
        {
            _localName = nil;
            _downpath = nil;
            [self downloadFileWith:_downPathMuArr];
        }
    }
    if (_allstartcomplete) {
        _allstartcomplete();
    }
}
//用于更改队列前的暂停下载，避免在更改队列时队列中数据发生改变的极端情况(也可以用做－－－－－全部暂停)
-(void)pauseDownload
{
    if (_task && ![_downpath isEqualToString:@""]) {
        __weak typeof(self) ws=self;
        //    取消下载任务
        [_task cancelByProducingResumeData:^(NSData *resumeData) {
            //resumeData包含暂停下载的位置和下载的url(一个很小的文件)
            [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
            ws.task = nil;
            _messagessDic[@"downcondition"] = @"pause";
            [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
            [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
            [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
            isDownLoading = NO;
            [self.delegate mangerDidPause];
        }];
    }else
    {
        [self.delegate mangerDidPause];
    }
}
//继续下载
-(void)resumeTask
{
    NSData *data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject]];
    
    NSData *resumeData;
    if (data) {
        resumeData = [self getCorrectResumeData:data];
    }
    if(!sessional)
    {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
        sessional = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:mainQueue];
    }
    if (resumeData) {
        _task =[sessional downloadTaskWithResumeData:resumeData];
    }else
    {
        _task = [sessional downloadTaskWithURL:[NSURL URLWithString:_downpath]];
    }
    _messagessDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject]];
    if (_messagessDic == nil || [_messagessDic allKeys] == 0) {
        _messagessDic = [NSMutableDictionary dictionary];
        _messagessDic[@"downcondition"] = @"";
        _messagessDic[@"allsize"] = @"";
        _messagessDic[@"contentsize"] = @"";
        _messagessDic[@"progress"] = @"";
    }
    _messagessDic[@"downcondition"] = @"download";
    [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
    //启动任务
    [_task resume];
    _lastName = _localName;
    isDownLoading = YES;
    [CoreStatus beginNotiNetwork:self];
    //    if(!_downTimer)
    //    {
    //        _downTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(restore) userInfo:nil repeats:YES];
    //        _count = 0;
    //
    //    }
    //    if (_timer) {
    //        [_timer invalidate];
    //        _timer = nil;
    //    }
}

//下载失败的代理
- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
{
    _timeCount = 0;
    _messagessDic[@"downcondition"] = @"failure";
    _messagessDic[@"allsize"] = @"";
    _messagessDic[@"contentsize"] = @"";
    _messagessDic[@"progress"] = @"";
    [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
    _downloadFailureBlock(error,_downpath,_localName);
    [_stopDownpathArr addObject:[_downpath mutableCopy]];
    [_stopStorageArr addObject:[_localName mutableCopy]];
    [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
    [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
    [_downPathMuArr removeObject:_downpath];
    [_storagePathMuArr removeObject:_localName];
    [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
    [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
    _localName = nil;
    _downpath = nil;
    if (_downPathMuArr.count >= 1 )
    {
        NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_downPathMuArr[0] componentsSeparatedByString:@"."].firstObject]];
        if ([messageDic[@"progress"] floatValue] != 0) {
            _localName = _storagePathMuArr[0];
            _downpath = _downPathMuArr[0];
            [self resumeTask];
        }else
        {
            _downpath = nil;
            _localName = nil;
            [self downloadFileWith:_downPathMuArr];
        }
    }
    else
    {
        isDownLoading = NO;
    }
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (error) {
        _timeCount = 0;
        if ([error.userInfo[@"NSLocalizedDescription"] isEqualToString:@"cancelled"]) {
            
            //        NSLog(@"-999出现了");
            //        NSData *resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
            //        [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
        }else
        {
            NSLog(@"%@",error);
            [_task cancel];
            _task = nil;
            sessional = nil;
            _timeCount = 0;
            _messagessDic[@"downcondition"] = @"failure";
            _messagessDic[@"allsize"] = @"";
            _messagessDic[@"contentsize"] = @"";
            _messagessDic[@"progress"] = @"";
            [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
            
            NSDictionary *resumeDataDic = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject]];
            if (resumeDataDic) {
                NSString *deletName = resumeDataDic[@"NSURLSessionResumeInfoTempFileName"];
                NSString *filePath1 = [NSString stringWithFormat:@"%@/%@",NSTemporaryDirectory(),deletName];
                [[NSFileManager defaultManager] removeItemAtPath:filePath1 error:nil];
                [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] error:nil];
            }
            _downloadFailureBlock(error,_downpath,_localName);
            if (_downpath != nil) {
                [_stopDownpathArr addObject:[_downpath mutableCopy]];
                
            }
            if (_localName != nil) {
                [_stopStorageArr addObject:[_localName mutableCopy]];
            }
            
            [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
            [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
            if (_downpath != nil) {
                [_downPathMuArr removeObject:_downpath];
            }
            if (_localName != nil) {
                [_storagePathMuArr removeObject:_localName];
            }
            [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
            [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
            _localName = nil;
            _downpath = nil;
            if (_downPathMuArr.count >= 1 )
            {
                NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_downPathMuArr[0] componentsSeparatedByString:@"."].firstObject]];
                if ([messageDic[@"progress"] floatValue] != 0) {
                    _localName = _storagePathMuArr[0];
                    _downpath = _downPathMuArr[0];
                    [self resumeTask];
                }else
                {
                    _downpath = nil;
                    _localName = nil;
                    [self downloadFileWith:_downPathMuArr];
                }
            }
            else
            {
                isDownLoading = NO;
            }
        }
    }
}
/**
 *  网络发生变化
 *  @param  NSNotification 通知
 */
-(void)coreNetworkChangeNoti:(NSNotification *)noti
{
    //判断是非时加载状态
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_async(queue, ^{
        if ([noti.userInfo[@"currentStatusEnum"] integerValue] != 1) {
            if (isDownLoading) {
                _timeCount = 0;
                [_timer invalidate];
                _timer = nil;
                [_task suspend];
                [_task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
                    [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
                }];
                for (NSString *storagePath in _storagePathMuArr) {
                    NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject]];
                    if (messagedic == nil) {
                        messagedic = [NSMutableDictionary dictionary];
                        messagedic[@"allsize"] = @"";
                        messagedic[@"contentsize"] = @"";
                        messagedic[@"progress"] = @"";
                    }
                    messagedic[@"downcondition"] = @"pause";
                    [messagedic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject] atomically:YES];
                }
                //将所有的队列中的数据变成暂停队列中的数据
                [_stopDownpathArr addObjectsFromArray:[_downPathMuArr mutableCopy]];
                [_stopStorageArr addObjectsFromArray:[_storagePathMuArr mutableCopy]];
                _downPathMuArr = [NSMutableArray array];
                _storagePathMuArr = [NSMutableArray array];
                [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
                [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
                [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
                [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
                isDownLoading = NO;
                if (_netBeakBlock) {
                    _netBeakBlock();
                }
            }
        }
    });
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
#pragma mark ----nsurlsession 下载的东西默认存放到lib中，建议下载后将它移动到自己设定的文件夹，并赋值相应的文件名
    //    将文件从tmp文件夹下移动到Library/Caches文件夹下
    //    nsurlsession 处理机制是在下载的过程中将数据保存在tmp中，如果程序中途退出，那么它会把下载的数据转移到cache
    //    在程序重新进入并再开始下载的时候它会把cache 中的数据重新复制到tmp中。
    _timeCount = 0;
    _messagessDic[@"downcondition"] = @"success";
    _downloadSuccessBlock(_downpath,_localName);
    [[NSNotificationCenter defaultCenter]  postNotificationName:@"downFinish" object:nil];
    [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",ContentLocations,_localName];
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:filePath error:nil];
    //移去resumdata
    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] error:nil];
    [self deleteCharecterWithlocalPath:_storagePathMuArr.firstObject];
    
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
#pragma mark ----在这里反向传值
    //    更新下载进度
    _progress=(double)totalBytesWritten/totalBytesExpectedToWrite;
    _lastByte = totalBytesWritten;
    _messagessDic[@"contentsize"] = [NSString stringWithFormat:@"%lld",totalBytesWritten];
    if (_downloadProgressBlock) {
        _downloadProgressBlock(_progress,totalBytesWritten,totalBytesExpectedToWrite);
    }
    if (_lastCount) {
        _lastCount([PhoneInsideStoreCount getContentLastSize]);
    }
    _messagessDic[@"allsize"] = [NSString stringWithFormat:@"%lld",totalBytesExpectedToWrite];
    _messagessDic[@"progress"] = [NSString stringWithFormat:@"%f",_progress];
    [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
    if(_isBackground)
    {
        if (_timeCount >= 2) {
            _timeCount = 0;
            [_task suspend];
            [_task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
                [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
                NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
                [mainQueue addOperationWithBlock:^{
                    [self resumeTask];
                }];
            }];
        }
    }
    //    _downbyte = totalBytesWritten;
    //    if (!_timer && _isTap == NO) {
    //        _stopName = _localName;
    //        [_task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
    //            [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
    //            if (!_timer) {
    //
    //                _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(restart) userInfo:nil repeats:NO];
    //            }
    //
    //        }];
    //    }else if (!_timer && _isTap)
    //    {
    //        [self puseLocal];
    //    }
}
//-(void)restart
//{
//    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
//    [mainQueue addOperationWithBlock:^{
//        if ([_stopName isEqualToString:_localName]) {
//            [self resumeTask];
//        }
//        [_timer invalidate];
//        _timer = nil;
//    }];
//}
-(BOOL)isNowDownForDownPath
{
    if (isDownLoading == YES) {
        return YES ;
    }
    else
    {
        return NO;
    }
}
#pragma marks-----程序退出或者进入后台方法
-(void)exitThePrograma:(NSNotification *)notify
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_timer invalidate];
    _timer = nil;
    [_task cancel];
    _task = nil;
    _messagessDic[@"downcondition"] = @"pause";
    [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
    [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
    [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
    for (NSString *storagePath in _storagePathMuArr) {
        NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject]];
        if (messagedic == nil) {
            messagedic = [NSMutableDictionary dictionary];
            messagedic[@"allsize"] = @"";
            messagedic[@"contentsize"] = @"";
            messagedic[@"progress"] = @"";
        }
        messagedic[@"downcondition"] = @"pause";
        BOOL success = [messagedic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject] atomically:YES];
        NSLog(@"%d",success);
        
    }
    for (NSString *storagePath in _stopStorageArr) {
        NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject]];
        if (messagedic == nil) {
            messagedic = [NSMutableDictionary dictionary];
            messagedic[@"allsize"] = @"";
            messagedic[@"contentsize"] = @"";
            messagedic[@"progress"] = @"";
        }
        messagedic[@"downcondition"] = @"pause";
        BOOL success =  [messagedic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject] atomically:YES];
        NSLog(@"%d",success);
    }
    //将所有的队列中的数据变成暂停队列中的数据
    [_stopDownpathArr addObjectsFromArray:_downPathMuArr];
    [_stopStorageArr addObjectsFromArray:_storagePathMuArr];
    _downPathMuArr = [NSMutableArray array];
    _storagePathMuArr = [NSMutableArray array];
    BOOL issuccess = NO;
    BOOL issuccess1 = NO;
    BOOL issuccess2 = NO;
    BOOL issuccess3 = NO;
    while (!issuccess || !issuccess1 || !issuccess2 || !issuccess3) {
        if (!issuccess) {
            NSLog(@"%@",ContentLocations);
            issuccess =  [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
        }else if (!issuccess1)
        {
            issuccess1 =  [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
        }else if (!issuccess2)
        {
            issuccess2 =  [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
        }else if (!issuccess3)
        {
            issuccess3 = [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
        }
    }
    isDownLoading = NO;
    [CoreStatus endNotiNetwork:self];
    _delegate = nil;
    _downloadProgressBlock = nil;
    _downloadSuccessBlock = nil;
    _downloadFailureBlock = nil;
    _netBeakBlock = nil;
    _pausefinishBolock = nil;
    _restartfinishBlock = nil;
    _deletfinishBlock = nil;
    _allstartcomplete = nil;
    _allstopcompelete = nil;
    _exitsuccess = nil;
    _alldeletsuccess = nil;
    _lastCount = nil;
    
    
}
-(void)deleteCharecterWithlocalPath:(NSString *)localPath
{
    if ([localPath isEqualToString:_storagePathMuArr.firstObject])
    {
        _progress = 0;
        _messagessDic = [NSMutableDictionary dictionary];
        _messagessDic[@"downcondition"] = @"";
        _messagessDic[@"allsize"] = @"";
        _messagessDic[@"contentsize"] = @"";
        _messagessDic[@"progress"] = @"";
    }
    if ([_storagePathMuArr containsObject:localPath]) {
        NSInteger index = [_storagePathMuArr indexOfObject:localPath];
        if (_storagePathMuArr.count == _downPathMuArr.count) {
            [_storagePathMuArr removeObjectAtIndex:index];
            [_downPathMuArr removeObjectAtIndex:index];
        }else
        {
            [self deleteAll];
            return;
        }
    }
    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] error:nil];
    [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
    [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
    _localName = nil;
    _downpath = nil;
    if (_storagePathMuArr.count == 0) {
        _task = nil;
        [_task cancel];
        sessional = nil;
        isDownLoading = NO;
    }else
    {
        if (_storagePathMuArr.count > 0) {
            NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_storagePathMuArr[0] componentsSeparatedByString:@"."].firstObject]];
            if ([messageDic[@"progress"] floatValue] != 0) {
                _localName = _storagePathMuArr[0];
                _downpath = _downPathMuArr[0];
                [self resumeTask];
            }else
            {
                _downpath = nil;
                _localName = nil;
                [self downloadFileWith:_downPathMuArr];
            }
        }
    }
}
#pragma mark ----程序后台下载结束调用
//- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
//{
//    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    if (appDelegate.backgroundSessionCompletionHandler && isDownLoading == NO) {
//        void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;
//        appDelegate.backgroundSessionCompletionHandler = nil;
//        if (completionHandler) {
//            completionHandler();
//        }
//    }
//}

-(void)deleteAll
{
    _localName = nil;
    _downpath = nil;
    [_task cancel];
    _task = nil;
    isDownLoading = NO;
    _messagessDic = [NSMutableDictionary dictionary];
    _storagePathMuArr = [NSMutableArray array];
    _downPathMuArr = [NSMutableArray array];
    [[NSFileManager defaultManager] removeItemAtPath:ContentLocations error:nil];
    NSArray *tmpPath = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:NSTemporaryDirectory() error:nil];
    for (NSString *path in tmpPath) {
        NSString *filpath = [NSTemporaryDirectory() stringByAppendingPathComponent:path];
        [[NSFileManager defaultManager] removeItemAtPath:filpath error:nil];
    }
    NSString *CachesPath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:CachesPath];
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue,^{
        for (NSString *p in files)
        {
            NSError *error;
            NSString *path = [CachesPath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path])
            {
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                //获取文件大小
                long long size = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] fileSize];
                NSLog(@"---==%lf",size/1024.0/1024.0);
            }
        }
        if (_alldeletsuccess) {
            _alldeletsuccess();
        }
    });
}
-(void)deletDownloadTaskwith:(NSMutableArray *)urlArr WithNameArr:(NSMutableArray *)nameArr WithUserFlag:(NSString *)userflag
{
    if (nameArr.count > 0) {
        if (isDownLoading == YES){
            if ([nameArr containsObject:_localName])
            {
                NSInteger index = [nameArr indexOfObject:_localName];
                [_task suspend];
                [_task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
                    [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[nameArr[index] componentsSeparatedByString:@"."].firstObject] atomically:YES];
                    _messagessDic[@"downcondition"] = @"pause";
                    [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[nameArr[index] componentsSeparatedByString:@"."].firstObject] atomically:YES];
                    NSMutableArray *mynameArr = [NSMutableArray arrayWithArray:[nameArr mutableCopy]];
                    _localName = nil;
                    _downpath = nil;
                    [self deletwithNameArr:mynameArr withUserflag:userflag];
                }];
            }else
            {
                [_task suspend];
                [_task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
                    [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
                    _messagessDic[@"downcondition"] = @"pause";
                    [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
                    NSMutableArray *mynameArr = [NSMutableArray arrayWithArray:[nameArr mutableCopy]];
                    [self deletwithNameArr:mynameArr withUserflag:userflag];
                }];
            }
        }else
        {
            [_task suspend];
            NSMutableArray *mynameArr = [NSMutableArray arrayWithArray:[nameArr mutableCopy]];
            [self deletwithNameArr:mynameArr withUserflag:userflag];
        }
    }
}
-(void)deletwithNameArr:(NSMutableArray *)nameArr withUserflag:(NSString *)userflag
{
    for (NSString *name in nameArr)
    {
        NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[name componentsSeparatedByString:@"."].firstObject]];
        if ([messagedic[@"downcondition"] isEqualToString:@"success"])
        {
            NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@/%@/%@",NSHomeDirectory(),userflag,_storagePath,name];
            [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
            [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/Documents/%@/%@/%@.plist",NSHomeDirectory(),userflag,_storagePath,[name componentsSeparatedByString:@"."].firstObject] error:nil];
            //移除 messagedic
            [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/Documents/%@/%@/%@messagedic.plist",NSHomeDirectory(),userflag,_storagePath,[name componentsSeparatedByString:@"."].firstObject] error:nil];
            NSInteger index = [nameArr indexOfObject:name];
            if (index == nameArr.count -1) {
                if (_storagePathMuArr.count > 0) {
                    NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_downPathMuArr[0] componentsSeparatedByString:@"."].firstObject]];
                    if ([messageDic[@"progress"] floatValue] != 0) {
                        _localName = _storagePathMuArr[0];
                        _downpath = _downPathMuArr[0];
                        [self resumeTask];
                    }else
                    {
                        _downpath = nil;
                        _localName = nil;
                        [self downloadFileWith:_downPathMuArr];
                    }
                }else
                {
                    _downpath = nil;
                    _localName = nil;
                    sessional = nil;
                    _task = nil;
                    isDownLoading = NO;
                }
            }
            continue;
        }
        NSDictionary *resumeDataDic = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[name componentsSeparatedByString:@"."].firstObject]];
        if (resumeDataDic) {
            NSString *deletName = resumeDataDic[@"NSURLSessionResumeInfoTempFileName"];
            NSString *filePath1 = [NSString stringWithFormat:@"%@/%@",NSTemporaryDirectory(),deletName];
            [[NSFileManager defaultManager] removeItemAtPath:filePath1 error:nil];
            [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[name componentsSeparatedByString:@"."].firstObject] error:nil];
        }
        //移除messageDic
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[name componentsSeparatedByString:@"."].firstObject] error:nil];
        if ([_stopStorageArr containsObject:name]) {
            NSInteger index = [_stopStorageArr indexOfObject:name];
            [_stopDownpathArr removeObjectAtIndex:index];
            [_stopStorageArr removeObjectAtIndex:index];
        }
        if ([_storagePathMuArr containsObject:name])
        {
            NSInteger index = [_storagePathMuArr indexOfObject:name];
            if (_downPathMuArr.count > index) {
               [_downPathMuArr removeObjectAtIndex:index];
            }
            if (_storagePathMuArr.count > index) {
                [_storagePathMuArr removeObjectAtIndex:index];
            }
        }
        [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
        [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
        [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
        [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
        NSInteger index = [nameArr indexOfObject:name];
        if (index == nameArr.count -1) {
            if (_storagePathMuArr.count > 0) {
                NSMutableDictionary *messageDic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_downPathMuArr[0] componentsSeparatedByString:@"."].firstObject]];
                if ([messageDic[@"progress"] floatValue] != 0) {
                    _localName = _storagePathMuArr[0];
                    _downpath = _downPathMuArr[0];
                    [self resumeTask];
                }else
                {
                    _downpath = nil;
                    _localName = nil;
                    [self downloadFileWith:_downPathMuArr];
                }
            }else
            {
                _downpath = nil;
                _localName = nil;
                sessional = nil;
                _task = nil;
                isDownLoading = NO;
            }
        }
    }
    if (_deletfinishBlock) {
        _deletfinishBlock();
    }
}

-(BOOL)isNowDownForDownPath:(NSString *)localPath
{
    BOOL isnowdownload = NO;
    if (isDownLoading)
    {
        NSDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[localPath componentsSeparatedByString:@"."].firstObject]];
        if (dic == nil || [dic[@"downcondition"] isEqualToString:@"download"] || [dic[@"downcondition"] isEqualToString:@"wait"]) {
            isnowdownload = YES;
        }else
        {
            isnowdownload = NO;
        }
    }
    return isnowdownload;
}
-(void)backgroundChange:(NSNotification *)notify
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // Do the work in background
        if (_task) {
            [_task suspend];
            [_task cancelByProducingResumeData:^(NSData *resumeData)
             {
                 [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
                 //先暂停保存下下载的reusmedata
                 NSOperationQueue *mainqueue = [NSOperationQueue mainQueue];
                 [mainqueue addOperationWithBlock:^{
                     if (_task) {
                         [self resumeTask];
                         _isBackground = YES;
                         if (!_timer) {
                             _timeCount = 0 ;
                             _timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
                         }else
                         {
                             [_timer setFireDate:[NSDate distantPast]];
                         }
                     }
                 }];
             }];
        }
    });
}
//多用户退出切换
-(void)exitTheprogram
{
    if (_timer)
    {
        [_timer  invalidate];
        _timer = nil;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    if (isDownLoading) {
        __weak typeof(self) ws=self;
        //    取消下载任务
        [_task suspend];
        [_task cancelByProducingResumeData:^(NSData *resumeData)
         {
             [resumeData writeToFile:[NSString stringWithFormat:@"%@/%@.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
             ws.task=nil;
             _messagessDic[@"downcondition"] = @"pause";
             [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
             for (NSString *storagePath in _storagePathMuArr) {
                 NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject]];
                 if (messagedic == nil) {
                     messagedic = [NSMutableDictionary dictionary];
                     messagedic[@"allsize"] = @"";
                     messagedic[@"contentsize"] = @"";
                     messagedic[@"progress"] = @"";
                 }
                 messagedic[@"downcondition"] = @"pause";
                 [messagedic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject] atomically:YES];
             }
             //将所有的队列中的数据变成暂停队列中的数据
             for (NSString *storagepath in _storagePathMuArr) {
                 NSInteger index = [_storagePathMuArr indexOfObject:storagepath];
                 [_stopDownpathArr addObject:[_downPathMuArr[index] mutableCopy]];
                 [_stopStorageArr addObject:[storagepath mutableCopy]];
             }
             _downPathMuArr = [NSMutableArray array];
             _storagePathMuArr = [NSMutableArray array];
             [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
             [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
             [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
             [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
             isDownLoading = NO;
             if (_exitsuccess) {
                 _exitsuccess();
             }
         }];
    }else
    {
        if (_storagePathMuArr.count != 0) {
            if (_localName != nil) {
                _messagessDic[@"downcondition"] = @"pause";
                [_messagessDic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[_localName componentsSeparatedByString:@"."].firstObject] atomically:YES];
            }
            for (NSString *storagePath in _storagePathMuArr) {
                NSMutableDictionary *messagedic = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject]];
                if (messagedic == nil) {
                    messagedic = [NSMutableDictionary dictionary];
                    messagedic[@"allsize"] = @"";
                    messagedic[@"contentsize"] = @"";
                    messagedic[@"progress"] = @"";
                }
                messagedic[@"downcondition"] = @"pause";
                [messagedic writeToFile:[NSString stringWithFormat:@"%@/%@messagedic.plist",ContentLocations,[storagePath componentsSeparatedByString:@"."].firstObject] atomically:YES];
            }
            //将所有的队列中的数据变成暂停队列中的数据
            for (NSString *storagepath in _storagePathMuArr) {
                NSInteger index = [_storagePathMuArr indexOfObject:storagepath];
                [_stopDownpathArr addObject:[_downPathMuArr[index] mutableCopy]];
                [_stopStorageArr addObject:[storagepath mutableCopy]];
            }
            _downPathMuArr = [NSMutableArray array];
            _storagePathMuArr = [NSMutableArray array];
            [_storagePathMuArr writeToFile:[NSString stringWithFormat:@"%@/storeArr.plist",ContentLocations] atomically:YES];
            [_downPathMuArr writeToFile:[NSString stringWithFormat:@"%@/downArr.plist",ContentLocations] atomically:YES];
            [_stopDownpathArr writeToFile:[NSString stringWithFormat:@"%@/stopurlArr.plist",ContentLocations] atomically:YES];
            [_stopStorageArr writeToFile:[NSString stringWithFormat:@"%@/stopstorageArr.plist",ContentLocations] atomically:YES];
        }
        isDownLoading = NO;
        if (_exitsuccess) {
            _exitsuccess();
        }
    }
}
-(void)gainLastCount
{
    _lastCount([PhoneInsideStoreCount getContentLastSize]);
}
@end
